import { RouteRecordRaw } from 'vue-router';

export const useMenuStore = defineStore('MenuStore', {
  state: () => ({
    isCollapse: false,
    menuList: getMenuList(),
    needKeepAlive: getNeedKeepAlive(),
  }),

  actions: {
    setCollapse() {
      this.isCollapse = !this.isCollapse;
    },
  },
});

function getMenuList() {
  const router = useRouter();
  const routes = router
    .getRoutes()
    .filter((route) => route.children.length > 0 && route.meta.isShow)
    .map((route) => {
      route.children = route.children.filter((r) => r.meta?.isShow);
      return route;
    });
  return routes;
}

const modules = import.meta.globEager('@/router/modules/**/*.ts');
const arr: string[] = [];
function getNeedKeepAlive(): string[] {
  Object.keys(modules).forEach((key) => {
    filterKeepAlive(modules[key].default);
  });
  return arr;
}
function filterKeepAlive(route: RouteRecordRaw): void {
  const repeatFlag = arr.some((el) => el === route.meta?.keepAliveName);
  if (repeatFlag) return;
  if (route.meta?.keepAliveName) arr.push(route.meta?.keepAliveName);
  if (route.children && route.children.length > 0) {
    route.children.forEach((item) => {
      filterKeepAlive(item);
    });
  }
}
